<?php
class DomBankLink_IdCard extends DomBankLink {
	
	const SSL_CLIENT_VERIFY = 'SSL_CLIENT_VERIFY';
	const SSL_CLIENT_VERIFY_SUCCESSFUL = 'SUCCESS';
	
	public function getName() {
		return 'IdCard';
	}
	
	public function getKey() {
		return 'IdCard';
	}
	
	public function getIconUrl() {
		return DOM_URL . '../libsPub/DomBankLink/images/IdCard.gif';
	}
	
	public function sendToBank( DomBankLinkObject $payment ) {
		header('location: '.DOM_URL.'../libsPub/DomBankLink/IdCardAuthStart/index.php?auth=1');
	}
	
	public function handleReplay( $paymentClassName, $requestId = NULL ) {

		$payment = DomAr::load( $requestId, $paymentClassName );
		
		if( !$payment ) {
			return false;
		}
		 
		if( $payment->status != DomBankPayment::SENT_TO_BANK ) {
			return $payment;
		}
			
		$payment->backTime = 'now';
		$payment->backIp = ip();
		
		if( isset($_SERVER['SSL_CLIENT_VERIFY']) && $_SERVER['SSL_CLIENT_VERIFY'] == 'SUCCESS' ) {
			$payment->status = 1;
		} else {
			$payment->status = 2;
		}
		
		$cardInfo = explode('/', $_SESSION['ID_CART_AUTH_DATA']);
		
		$parameters = array ();
		foreach ($cardInfo as $info) {
			if ($info != null) {
				$parameterArray = explode('=', $info);
				$parameters[$parameterArray[0]] = $this->decodeToUtf8($parameterArray[1]);
			}
		}
		
		$payment->clientCode = $parameters['serialNumber'];
		$payment->clientName = $parameters['GN'].' '.$parameters['SN'];
		
		if( !$payment->save() ) {
			throw new RuntimeException( $payment->getValidationMessages('<br>') );
		}
	}
	
	/**
	 * Decodes id-card information to utf8
	 *
	 * @param String $str String to decode
	 * @return String Decoded string
	 */
	private function decodeToUtf8($str) {
		$str = preg_replace("/\\\\x([0-9ABCDEF]{1,2})/e", "chr(hexdec('\\1'))", $str);
		$result = '';
		$encoding = mb_detect_encoding($str, 'ASCII, UCS2, UTF8');
		if($encoding == 'ASCII') {
			$result = mb_convert_encoding($str, 'UTF-8', 'ASCII');
		} else {
			if(substr_count($str, chr(0)) > 0) {
				$result = mb_convert_encoding($str, 'UTF-8', 'UCS2');
			} else {
				$result = $str;
			}
		}

		return $result;
	}
	
}
?>